//
//  LoginViewController.m
//  Vpay
//
//  Created by 伟大大 on 2018/9/15.
//  Copyright © 2018年 丁伟佳. All rights reserved.
//

#import "LoginViewController.h"
#import "ResignViewController.h"
#import "FindPassViewController.h"
#import "NSBundle+Language.h"
#import "SYViewController.h"

#import "WKVerCodeImageView.h"
@interface LoginViewController () {
    int height;
}

@property (nonatomic, strong) WKVerCodeImageView *codeImageView;


@end

@implementation LoginViewController {
    NSString *str;

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
//    [theApp hiddenBottomView];
    navigationImageView.hidden = YES;
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    //    self.navigationController.navigationBar.barTintColor = TITLECOLOR;
    self.navigationController.delegate = self;
//    _login_name_textfield.text = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWNO];
//    _login_pass_textfield.text = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWPass];
    
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [theApp showBottomView];
    navigationImageView.hidden = NO;
//    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    //    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    //        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    //    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    navigationImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    self.view = [[[NSBundle mainBundle]loadNibNamed:@"LoginViewController" owner:self options:nil]lastObject];
    
//    self.login_bg_imageView.userInteractionEnabled = NO;
    
    [self initViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
- (void)initViews{
    
    //    self.login_bg_imageView.frame = CGRectMake(0, 0, 320*theApp.autoSizeScaleX, 569*theApp.autoSizeScaleY+20);
    self.Login_btn.layer.cornerRadius = 4.5;
    
    _pass_textfiled.secureTextEntry = YES;
    _pass_textfiled.delegate = self;
    _phone_textfiled.delegate = self; 
    _YZM_textfiled.delegate = self;

    self.ChangeLanguage_btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    self.Resign_btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.Forget_btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    _login_name_textfield.text = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWNO];
//    _login_pass_textfield.text = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWPass];
    
    self.phone_label.text = NSLocalizedString(@"phone", nil);
    self.pass_label.text = NSLocalizedString(@"pass", nil);
    
    self.phone_textfiled.placeholder = NSLocalizedString(@"account", nil);
    self.pass_textfiled.placeholder = NSLocalizedString(@"password", nil);


    [self.Resign_btn setTitle:NSLocalizedString(@"newregist", nil) forState:UIControlStateNormal];
    [self.Forget_btn setTitle:NSLocalizedString(@"forget", nil) forState:UIControlStateNormal];
    
    [self.Login_btn setTitle:NSLocalizedString(@"denglu", nil) forState:UIControlStateNormal];

    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouched)];
    //    tap.delegate = self;
    [self.view addGestureRecognizer:tap1];
    
    if (([[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] isEqualToString:@"zh-Hans"] && ![[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] isEqualToString:@""])||![[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"]) {
        
        [self.ChangeLanguage_btn setTitle:@"Change English" forState:UIControlStateNormal];
        

        
    }else {
        [self.ChangeLanguage_btn setTitle:@"切换中文" forState:UIControlStateNormal];
        
        [self.phone_label setFrame:CGRectMake(self.phone_label.frame.origin.x, self.phone_label.frame.origin.y-4*theApp.autoSizeScaleY, self.phone_label.frame.size.width, self.phone_label.frame.size.height)];
        
        [self.image1 setFrame:CGRectMake(self.image1.frame.origin.x, self.image1.frame.origin.y-4*theApp.autoSizeScaleY, self.image1.frame.size.width, self.image1.frame.size.height)];
        
        [self.phone_textfiled setFrame:CGRectMake(self.phone_label.frame.origin.x, self.phone_label.frame.origin.y+self.phone_label.frame.size.height+3*theApp.autoSizeScaleY, self.phone_textfiled.frame.size.width, self.phone_textfiled.frame.size.height)];
        
        [self.spliteView1 setFrame:CGRectMake(self.image1.frame.origin.x, self.phone_textfiled.frame.origin.y+self.phone_textfiled.frame.size.height, self.spliteView1.frame.size.width, self.spliteView1.frame.size.height)];
        
        
        [self.pass_label setFrame:CGRectMake(self.phone_label.frame.origin.x, self.spliteView1.frame.origin.y+self.spliteView1.frame.size.height+6*theApp.autoSizeScaleY, self.pass_label.frame.size.width, self.pass_label.frame.size.height)];
        
        [self.image2 setFrame:CGRectMake(self.image2.frame.origin.x, self.pass_label.frame.origin.y+1*theApp.autoSizeScaleY, self.image2.frame.size.width, self.image2.frame.size.height)];

        
        [self.pass_textfiled setFrame:CGRectMake(self.pass_label.frame.origin.x, self.pass_label.frame.origin.y+self.pass_label.frame.size.height+3*theApp.autoSizeScaleY, self.pass_textfiled.frame.size.width, self.pass_textfiled.frame.size.height)];
        
        [self.spliteView2 setFrame:CGRectMake(self.image2.frame.origin.x, self.pass_textfiled.frame.origin.y+self.pass_textfiled.frame.size.height, self.spliteView2.frame.size.width, self.spliteView2.frame.size.height)];
        
        [self.Resign_btn setFrame:CGRectMake(self.Resign_btn.frame.origin.x, self.spliteView2.frame.origin.y+7*theApp.autoSizeScaleY, self.Resign_btn.frame.size.width, self.Resign_btn.frame.size.height)];
        
        [self.Forget_btn setFrame:CGRectMake(self.Forget_btn.frame.origin.x, self.Resign_btn.frame.origin.y, self.Forget_btn.frame.size.width, self.Forget_btn.frame.size.height)];
        
        
        [self.Login_btn setFrame:CGRectMake(self.Login_btn.frame.origin.x, self.Forget_btn.frame.size.height+self.Forget_btn.frame.origin.y+62*theApp.autoSizeScaleY, self.Login_btn.frame.size.width, self.Login_btn.frame.size.height)];

    }
    SLog(@"当前语言 %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"]);
    
    
    _codeImageView = [[WKVerCodeImageView alloc] initWithFrame:CGRectMake([AppUtility screenWidth]-10*theApp.autoSizeScaleX-70*theApp.autoSizeScaleX, 308*theApp.autoSizeScaleY, 70*theApp.autoSizeScaleX, 25*theApp.autoSizeScaleY)];
    _codeImageView.bolck = ^(NSString *imageCodeStr){//看情况是否需要
        NSLog(@"imageCodeStr = %@",imageCodeStr);
        str=[NSString stringWithFormat:@"%@", imageCodeStr];
    };
    //是否需要斜体
    _codeImageView.isRotation = YES;
    [_codeImageView freshVerCode];
    
    //点击刷新
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [_codeImageView addGestureRecognizer:tap];
    [self.myScrollView addSubview: _codeImageView];
    
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    height = keyboardRect.size.height;
    
    [self.myScrollView setContentOffset:CGPointMake(0, 100) animated:YES];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification{
    
    [self.myScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)tapClick:(UITapGestureRecognizer*)tap
{
    [_codeImageView freshVerCode];
    
}
-(void)tapTouched{
    
    if ([_phone_textfiled isFirstResponder]) {
        [_phone_textfiled resignFirstResponder];
    }
    
    if ([_pass_textfiled isFirstResponder]) {
        [_pass_textfiled resignFirstResponder];
    }
    if ([_YZM_textfiled isFirstResponder]) {
        [_YZM_textfiled resignFirstResponder];
    }
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)dealloc {
    [_phone_textfiled release];
    [_pass_textfiled release];
    [_Login_btn release];
    [_Resign_btn release];
    [_Forget_btn release];
    [_ChangeLanguage_btn release];
    [_phone_label release];
    [_pass_label release];
    [_spliteView1 release];
    [_spliteView2 release];
    [_image1 release];
    [_image2 release];
    [_YZM_textfiled release];
    [_myScrollView release];
    [super dealloc];
}
- (IBAction)Resign_btnClik:(UIButton *)sender {
    
    ResignViewController *vc = [[ResignViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)ForgetPass_btnClik:(UIButton *)sender {
    
    FindPassViewController *vc = [[FindPassViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)Login_btnClik:(UIButton *)sender {
    //登录
    NSString *number = _phone_textfiled.text;
    if ([number isKindOfClass:[NSNull class]] || [number length]==0) {
//        [@"帐号不能为空" showAlert];
        [self.view makeToast:NSLocalizedString(@"phonets", nil)];
        return;
    }
    NSString *pass = _pass_textfiled.text;
    if ([pass isKindOfClass:[NSNull class]] || [pass length]==0) {
//        [@"密码不能为空" showAlert];
        [self.view makeToast:NSLocalizedString(@"passts", nil)];
        return;
    }
    BOOL result1 =  [_YZM_textfiled.text compare:str
                                    options:NSCaseInsensitiveSearch | NSNumericSearch]==NSOrderedSame;
    
    if (result1) {
        NSLog(@"succes");
    }else{
        [self.view makeToast:@"验证码输入错误"];
        return;
    }
    //    NSString *strDeviceToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]                  stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
    //    NSString *postStr = [NSString stringWithFormat:@"username=%@&enPassword=%@",_numberField.text,_passField.text];
    
    NSString *postStr = [NSString stringWithFormat:@"account=%@&password=%@&isApp=1",_phone_textfiled.text,_pass_textfiled.text];



    NSDictionary *resultDict = [NetUtility getDataWithURLStr:KURLLogin andPostStr:postStr];


    //    NSDictionary *resultDict =[NetUtility getDataWithURLStr:[NSString stringWithFormat:@"%@%@",KURLLogin,postStr] andPostStr:nil];
    UEXNSLog(@"KURL===%@%@ resultDict=%@",KURLLogin,postStr, resultDict);

    if (resultDict) {
        int stauts = [[resultDict objectForKey:@"s"] intValue];

        if (stauts==1) {


            [[NSUserDefaults standardUserDefaults] setObject:number forKey:KUDAppTDWNO];
            [[NSUserDefaults standardUserDefaults] setObject:pass forKey:KUDAppTDWPass];
            [[NSUserDefaults standardUserDefaults] synchronize];

            [AccountController setAccountState:kAccountStateLogin];
            [AccountController setAccountInfo:[resultDict objectForKey:@"d"]];




            //            [self.navigationController popViewControllerAnimated:YES];

            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLogin"]) {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLogin"];

            }
            else
            {
                [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLogin"];

            }

//            [JPUSHService setAlias:[resultDict objectForKey:@"d"][@"alias"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
//                SLog(@"执行结果:%ld",(long)iResCode);
//            } seq:1];
//
//
//            SLog(@"role == %@",[[AccountController getAccountInfo] objectForKey:@"role"]);

            [self.navigationController.view makeToast:[resultDict objectForKey:@"i"] ];

            [theApp enterHomePage];




        }else{
            [self.navigationController.view makeToast:[resultDict objectForKey:@"i"] ];
        }


    }
    
//    [theApp enterHomePage];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    //    if (textField.tag==110||textField.tag==111||textField.tag==112) {
    //        if (![AppUtility validateNumber:string]) {
    //            [self.view makeToast:@"请输入数字"];
    //            [textField resignFirstResponder];
    //            textField.text = @"";
    //        }
    //        return [AppUtility validateNumber:string];
    //    }
    //    else{
    //
    //        return YES;
    //    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
    if (textField == _YZM_textfiled) {
        BOOL result1 =  [textField.text compare:str
                                        options:NSCaseInsensitiveSearch | NSNumericSearch]==NSOrderedSame;
        
        if (result1) {
            NSLog(@"succes");
        }else{
            [self.view makeToast:@"验证码输入错误"];
        }
    }
    
    return YES;
}
- (IBAction)ChangeLanguage_btnClik:(UIButton *)sender {
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] isEqualToString:@"zh-Hans"] && ![[[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"] isEqualToString:@""]) {
        
        [self changeLanguageTo:@"en"];
        
        
    }else {
        [self changeLanguageTo:@"zh-Hans"];

    }
}
- (void)changeLanguageTo:(NSString *)language {
    // 设置语言
    [NSBundle setLanguage:language];
    
    // 然后将设置好的语言存储好，下次进来直接加载
    [[NSUserDefaults standardUserDefaults] setObject:language forKey:@"myLanguage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 我们要把系统windown的rootViewController替换掉
    LoginViewController *HomeController = [[LoginViewController alloc] init];
    UINavigationController *HomeNavController = [[UINavigationController alloc] initWithRootViewController:HomeController];
    
    [UIApplication sharedApplication].keyWindow.rootViewController = HomeNavController;
    // 跳转到设置页
//    tab.selectedIndex = 2;
}
@end
